package cc.yugu.yhdw.webserver.web.controller.security.hdw;

import cc.yugu.yhdw.common.annotation.ViewModel;
import cc.yugu.yhdw.common.constant.ConstEnum;
import cc.yugu.yhdw.common.constant.Constant;
import cc.yugu.yhdw.common.domain.basic.UpgradePack;
import cc.yugu.yhdw.common.domain.basic.User;
import cc.yugu.yhdw.common.domain.hdw.Agency;
import cc.yugu.yhdw.common.domain.hdw.Cabinet;
import cc.yugu.yhdw.common.domain.hdw.Supplier;
import cc.yugu.yhdw.common.entity.json.DataResult;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.json.PageResult;
import cc.yugu.yhdw.common.utils.HttpClientUtils;
import cc.yugu.yhdw.common.utils.HttpUtils;
import cc.yugu.yhdw.common.utils.IdUtils;
import cc.yugu.yhdw.common.utils.YhdwUtils;
import cc.yugu.yhdw.webserver.biz.client.ClientBizUtils;
import cc.yugu.yhdw.webserver.constant.AppConstEnum;
import cc.yugu.yhdw.webserver.entity.SessionUser;
import cc.yugu.yhdw.webserver.service.hdw.AgencyService;
import cc.yugu.yhdw.webserver.service.hdw.CabinetPropertyService;
import cc.yugu.yhdw.webserver.service.hdw.CabinetService;
import cc.yugu.yhdw.webserver.service.hdw.SupplierService;
import cc.yugu.yhdw.webserver.web.controller.security.SecurityController;
import freemarker.template.EmptyMap;
import org.apache.bcel.generic.NEW;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(value = "/security/hdw/cabinet")
public class CabinetController extends SecurityController {
    final static String UPLOAD_URL = "/security/cabinet_log/upload.htm";

    @Autowired
    CabinetService cabinetService;
    @Autowired
    CabinetPropertyService cabinetPropertyService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    AgencyService agencyService;

    @RequestMapping(value = "index.htm")
    public void index(Model model) {
        model.addAttribute(MENU_CODE_NAME, AppConstEnum.Menu.MENU_02_01.getValue());
    }

    @ResponseBody
    @ViewModel(ViewModel.JSON)
    @RequestMapping(value = "unique.htm")
    public ExtResult unique(String id) {
        return cabinetService.findUnique(id);
    }

    @RequestMapping("page.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public PageResult page(Cabinet search, HttpServletRequest request) {
        if (getSessionUser(request).getType() == User.Type.AGENT.getValue()) {
            search.setAgentId(getSessionUser(request).getAgentId());
        } else if (getSessionUser(request).getType() == User.Type.AGENCY.getValue()) {
            search.setAgencyId(getSessionUser(request).getAgencyId());
        }
        return PageResult.successResult(cabinetService.findPage(search));
    }

    @RequestMapping(value = "image.htm", method = RequestMethod.GET)
    public void image(String num, Model model) {
        model.addAttribute("num", num);
    }

    @RequestMapping(value = "image.htm", method = RequestMethod.POST)
    public String image(@RequestParam("file") MultipartFile file, int num, Model model) throws IOException {
        File sourceFile = new File(getAppConfig().tempDir, IdUtils.uuid() + "." + YhdwUtils.getFileSuffix(file.getOriginalFilename()));
        YhdwUtils.makeParentDir(sourceFile);
        file.transferTo(sourceFile);

        Map<String, File> fileMap = new HashMap<String, File>();
        fileMap.put("file", sourceFile);
        HttpClientUtils.HttpResp httpResp = HttpClientUtils.uploadFile(getAppConfig().staticUrl + "/security/hdw_upload/cabinet_image.htm", fileMap, Collections.EMPTY_MAP, YhdwUtils.buildHttpHeader(System.currentTimeMillis(), getAppConfig().uploadSalt));
        if (httpResp.status / 100 != 2) {
            model.addAttribute("message", "上传静态服务器失败");
            return "/security/hdw/cabinet/image_response";
        }

        Map map = (Map) YhdwUtils.decodeJson(httpResp.content, Map.class);
        Map data = (Map) map.get("data");

        String imagePath = (String) data.get("filePath");

        model.addAttribute("success", true);
        model.addAttribute("filePath", imagePath);
        model.addAttribute("fileName", sourceFile.getName());
        model.addAttribute("num", num);

        return "/security/hdw/cabinet/image_response";
    }

    @RequestMapping(value = "add.htm")
    public void add(Model model) {
        model.addAttribute("powerSupplierList", supplierService.findByType(Supplier.Type.POWER.getValue()));
        model.addAttribute("cabinetSupplierList", supplierService.findByType(Supplier.Type.CABINET.getValue()));
    }

    @RequestMapping(value = "edit.htm")
    public String edit(Model model, String id) {
        model.addAttribute("id", id);
        return "/security/hdw/cabinet/edit";
    }

    @RequestMapping("create.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult create(Cabinet terminal) {
        return cabinetService.insert(terminal);
    }

    @RequestMapping(value = "edit_basic.htm")
    public String editBasic(Model model, String id) {
        Cabinet entity = cabinetService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        model.addAttribute("powerSupplierList", supplierService.findByType(Supplier.Type.POWER.getValue()));
        model.addAttribute("cabinetSupplierList", supplierService.findByType(Supplier.Type.CABINET.getValue()));

        return "/security/hdw/cabinet/edit_basic";
    }

    @RequestMapping(value = "edit_location.htm")
    public String editLocation(Model model, int editFlag, String id) {
        Cabinet entity = cabinetService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        model.addAttribute("editFlag", editFlag);
        return "/security/hdw/cabinet/edit_location";
    }

    @RequestMapping(value = "edit_property.htm")
    public String editProperty(Model model, int editFlag, String id) {
        Cabinet entity = cabinetService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
            model.addAttribute("list", cabinetPropertyService.findByCabinet(id));
        }
        model.addAttribute("editFlag", editFlag);
        return "/security/hdw/cabinet/edit_property";
    }

    @RequestMapping(value = "edit_image.htm")
    public String editImage(Model model, String id) {
        Cabinet entity = cabinetService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/hdw/cabinet/edit_image";
    }

    @RequestMapping(value = "edit_temperature.htm")
    public String editTemperature(Model model, String[] cabinetId) throws Exception {
        model.addAttribute("cabinetId", YhdwUtils.encodeJson(cabinetId));
        return "/security/hdw/cabinet/edit_temperature";
    }

    @RequestMapping(value = "usageLog.htm")
    public void usageLog(Model model, String id) {
        model.addAttribute("id", id);
    }

    @ViewModel(ViewModel.JSON)
    @ResponseBody
    @RequestMapping(value = "findUsageLog.htm")
    public ExtResult findUsageLog(Date date, String id) {
        List<String> entity = cabinetService.findUsageLog(date, id);
        return DataResult.successResult(entity);
    }

    @ViewModel(ViewModel.JSON)
    @ResponseBody
    @RequestMapping(value = "findUsageLogCount.htm")
    public ExtResult findUsageLogCount(String id) {
        List<String> entity = cabinetService.findUsageLogCount(id);
        return DataResult.successResult(entity);
    }

    @RequestMapping("update_basic.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult updateBasic(Cabinet entity) {
        return cabinetService.updateBasic(entity);
    }

    @RequestMapping("update_location.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult updateLocation(Cabinet entity) {
        return cabinetService.updateLocation(entity);
    }

    @RequestMapping("update_image.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult updateImage(Cabinet entity) {
        return cabinetService.updateImage(entity);
    }

    @RequestMapping("update_property.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult updateProperty(String id, int[] active, String[] property, String[] value) {
        ExtResult extResult = cabinetPropertyService.insert(id, active, property, value);
        if (extResult.isSuccess()) {
            ClientBizUtils.noticeTerminalProperty(getAppConfig(), id);
        }
        return extResult;
    }

    @RequestMapping("update_temperature.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult updateTemperature(String cabinetId, byte fst, byte fot, byte pt, byte rpt) throws Exception {
        return cabinetService.updateTemperature((String[]) YhdwUtils.decodeJson(cabinetId, String[].class), fst, fot, pt, rpt);
    }

    @RequestMapping("delete.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public ExtResult delete(String id) {
        return cabinetService.delete(id);
    }

    @RequestMapping(value = "view.htm")
    public String view(Model model, String id) {
        model.addAttribute("id", id);
        return "/security/hdw/cabinet/view";
    }

    @RequestMapping(value = "view_image.htm")
    public String view_image(Model model, String id) {
        Cabinet entity = cabinetService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/hdw/cabinet/view_image";
    }

    @RequestMapping(value = "view_basic.htm")
    public String view_basic(Model model, String id) {
        Cabinet entity = cabinetService.find(id);
        if (entity == null) {
            return SEGMENT_RECORD_NOT_FOUND;
        } else {
            model.addAttribute("entity", entity);
        }
        return "/security/hdw/cabinet/view_basic";
    }

    @RequestMapping(value = "downloadLog.htm")
    public String downloadLog(Model model, String id) {
        model.addAttribute("cabinetId", id);
        model.addAttribute("logType", Cabinet.LogType.values());
        return "/security/hdw/cabinet/downloadLog";
    }

    @ResponseBody
    @ViewModel(ViewModel.JSON_ARRAY)
    @RequestMapping(value = "uploadLog.htm")
    public ExtResult uploadLog(Model model, String id, int type, String date) throws Exception {
        return ClientBizUtils.upload(appConfig, id, type, date, getAppConfig().staticUrl + UPLOAD_URL);
    }

    @ResponseBody
    @ViewModel(ViewModel.JSON_ARRAY)
    @RequestMapping(value = "tree.htm")
    public void tree(Cabinet search, String dummy, HttpServletResponse response) throws Exception {
        response.setContentType(ConstEnum.ContentType.JSON.getValue());
        cabinetService.tree(search, dummy, response.getOutputStream());
    }

    /**
     * 柜机分布图展示
     * @Param []
     * @Return cc.yugu.yhdw.common.entity.json.DataResult
     * @Author zxj 2018/8/28
     */
    @RequestMapping(value = "coordinate.htm")
    @ViewModel(ViewModel.JSON)
    @ResponseBody
    public DataResult coordinate() {
        return DataResult.successResult(cabinetService.findAll());
    }

}
